<template>
  <basic-container>
    <el-tabs v-model="activeName" @tab-click="handleClick" class="chart-tab tab-font" type="border-card">
      <el-tab-pane label="其他" name="other"></el-tab-pane>
      <el-tab-pane label="外部" name="out"></el-tab-pane>
      <avue-crud
        v-if="activeName === 'other'"
        :option="option"
        :table-loading="loading"
        v-model="form"
        :data="data"
        :page.sync="page"
        :search.sync="query"
        :permission="permissionList"
        :before-open="beforeOpen"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @selection-change="selectionChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot="subTypeSearch">
          <el-select v-model="query.subType" placeholder="请选择业务小类" :clearable="true">
            <el-option v-for="cateItem in subTypeList" :key="cateItem.value" :label="cateItem.label" :value="cateItem.value"></el-option>
          </el-select>
        </template>
        <template slot="menuRight">
          <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete">删 除</el-button>
        </template>
        <template slot-scope="{ row }" slot="menu">
          <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-view" @click="handleView(row)">详情</el-button>
        </template>
      </avue-crud>
      <packid-validate-config v-else></packid-validate-config>
    </el-tabs>
    <!-- 编辑新增弹窗-->
    <add-serial-number ref="addSnNumber" :visible.sync="editVisible" :title="editTitle" @closeDialog="handleCloseDialog"></add-serial-number>
    <!-- 详情弹窗-->
    <view-serial-number ref="viewSnNumber" :visible.sync="viewVisible"></view-serial-number>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import addSerialNumber from '@/views/product/components/addSerialNumber';
import viewSerialNumber from '@/views/product/components/viewSerialNumber';
import { getSeqNoRules, subTypeMap } from '@/util/global';
import { getList, remove } from '@/api/admin/sequencedefinition';
import { getCategory } from '@/api/warehouse/materialRules';
import packidValidateConfig from '@/views/admin/packid-validate-config.vue';

export default {
  name: 'serialNumberConfig', // 会渲染成传入的componentName
  components: {
    userTableConfig,
    addSerialNumber,
    viewSerialNumber,
    packidValidateConfig
  },
  data() {
    return {
      activeName: 'other',
      form: {},
      seqNoRulesList: getSeqNoRules(),
      editTitle: '新增',
      editVisible: false,
      viewVisible: false,
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      subTypeList: [],
      selectionList: [],
      data: [],
      rowData: {},
      option: {
        height: 'calc(100vh - 480px)',
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        selection: true,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: true,
        addBtn: false,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sysSerial',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            change: ({ column, value }) => {
              this.getSubTypeData(value);
            },
            search: true
          },
          {
            label: '小类',
            prop: 'subType',
            formatter: (row) => {
              return subTypeMap[row.subType] || '';
            },
            fromslot: true,
            type: 'select',
            search: true
          },
          {
            label: '规则名称',
            prop: 'name',
            search: true
          },
          {
            label: '序列号ID',
            prop: 'code',
            search: true
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNo'
          },
          {
            label: '进制类型',
            // prop: 'baseType',
            prop: 'hexType',
            span: 8,
            dicData: [
              {
                label: '十进制',
                value: '10'
              },
              {
                label: '十六进制',
                value: '16'
              },
              {
                label: '自定义',
                value: 'custom'
              }
            ],
            formatter: (val) => {
              // 回显进制
              if (!val.hexType) {
                // 兼容问题历史数据  之前没有这个字段 现在有了. 对于之前数据走这个逻辑
                if (val.hexString === '0123456789') {
                  return '十进制';
                } else if (val.hexString === '0123456789ABCDEF') {
                  return '十六进制';
                } else {
                  return '自定义';
                }
              }
            }
          },
          {
            label: '清零类型',
            prop: 'regressionType',
            type: 'select',
            value: 'Year',
            dicData: [
              {
                label: '不清零',
                value: ''
              },
              {
                label: '年',
                value: 'Year'
              },
              {
                label: '月',
                value: 'Month'
              },
              {
                label: '周',
                value: 'Week'
              },
              {
                label: '日',
                value: 'Day'
              }
            ]
          },
          {
            label: '序列号构成规则',
            prop: 'sequenceNoFormat'
          },
          {
            label: '创建人',
            prop: 'createUserName'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          },
          {
            label: '最后修改人名称',
            prop: 'updateUserName'
          },
          {
            label: '最后修改时间',
            prop: 'updateTime'
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      this.$refs.crud.dicInit('cascader');
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission, false),
        viewBtn: this.vaildData(this.permission, false),
        delBtn: this.vaildData(this.permission, false),
        editBtn: this.vaildData(this.permission, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    rowSave(row, done, loading) {},
    rowUpdate(row, index, done, loading) {},
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    beforeOpen(done, type) {},
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    handleCloseDialog() {
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleAdd() {
      this.editVisible = true;
      this.editTitle = '新增';
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleEdit(row) {
      this.editVisible = true;
      this.editTitle = '编辑';
      this.$refs.addSnNumber.getRowData(row.id);
    },
    handleView(row) {
      this.viewVisible = true;
      this.$refs.viewSnNumber.getRowData(row.id);
    },
    async getSubTypeData(val) {
      try {
        const res = await getCategory({ code: val });
        this.subTypeList = (res.data.data || []).map((item) => ({
          label: item.dictValue,
          value: item.dictKey
        }));
      } catch (e) {
        console.warn(e);
      }
    },
    filterEmptyValues(obj) {
      for (let key in obj) {
        if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
          delete obj[key];
        }
      }
      return obj;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      const obj = this.filterEmptyValues(Object.assign(params, this.query));
      getList(page.currentPage, page.pageSize, obj)
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.data.forEach((ele) => {
            ele.sequencenoformat = ele.sequenceNoFormat;
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleClick() {
      this.$nextTick(() => {
        this.$structuralSplit('外部规则');
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}
</style>
